import pandas as pd
from arrangement_utils import *
from split_utils import *
from wash_utils import *
from verify_utils import *
import time
import os
import shutil


if __name__ == '__main__':

    # 使用说明 -----------------------------------
    time.sleep(1)
    print('===========================================================')
    print('简单说明：使用正则表达式整理excel表中不规范的目录，初步整理成需求格式')
    print('PS:')
    print('1.文件夹下需要有一个excel（只放一个，名称随意），其中一列“目录”保存着待整理的目录')
    print('2.拆分后的excel将新增一列整理结果列，命名为“[整理]目录”')
    print('===========================================================')
    time.sleep(0.5)
    # ------------------------------------------

    # 输入操作路径 ----------------------------------------------------------------
    operate_dir = input('请输入excel目录（旺柴）:')  # D:\PycharmProjects\spiders\图片下载工具\excel
    operate_dir = os.path.abspath(operate_dir)
    # operate_dir = os.path.abspath(r'C:\Users\cxstar46\Desktop\正则表达式题名拆分测试')
    # -----------------------------------------------------------------------------

    # 读取配置文件 --------------------------------------
    # 只有功能1读取“原题名”存入“拆分后元数据内容”，其他程序都是读取“拆分后元数据内容”存入“拆分后元数据内容”
    source_title_col = '目录'

    # 检测excel数量，只能放一个，当只有一个excel时，提取它的路径excel_path -------
    print('检查路径下的文件格式...')
    excel_name = None
    excel_count = 0
    file_list = os.listdir(operate_dir)
    for file in file_list:
        if file.endswith('.xlsx') or file.endswith('.xlx'):
            excel_count += 1
            excel_name = file
    if excel_count == 0:
        input('文件夹下没有excel，按任意键退出...')
        raise Exception(0)
    if excel_count > 1:
        input('只能放一个excel，按任意键退出...')
        raise Exception(0)
    # print(excel_name)
    # raise Exception(1212)
    # ----------------------------------------------------------------------
    # print(excel_path)
    # print(img_dir)

    # 读取excel ----------------------------------------
    excel_path = os.path.join(operate_dir, excel_name)
    # print(excel_path)
    try:
        df = pd.read_excel(excel_path)
        df = df.where(df.notnull(), None)
    except Exception as e:
        print(e)
        print('文件不存在或已损坏...')
        input('按任意键退出...')
        raise Exception('123')
    # -------------------------------------------------

    # 备份原始excel表 --------------------------------------------------------------
    print('备份excel...')
    bak_dir = '目录整理前的备份'
    file_list = os.listdir(operate_dir)
    if bak_dir not in file_list:
        os.makedirs(os.path.join(operate_dir, bak_dir))
    bak_excel_path = os.path.join(os.path.join(operate_dir, bak_dir), excel_name)
    shutil.copyfile(excel_path, bak_excel_path)
    # -----------------------------------------------------------------------------


    all_mulu_list = []        # 目录整理结果列
    all_verify_res_list = []  # 目录审核结果列

    for i in range(df.shape[0]):
        print(i)

        mulu = df.loc[i, source_title_col]
        print('mulu: {}'.format(mulu))

        # 目录为空 跳过
        if isNaNo(mulu):
            print('目录为空 跳过')
            all_mulu_list.append(None)
            all_verify_res_list.append(None)
            continue

        # 目录切分
        mulu_list = mulu_split(mulu)

        # 目录清洗
        mulu_list = wash_mulu(mulu_list)

        # for item in mulu.split('\n'):
        #     print(item)

        # 目录整理
        mulu_list = mulu_arrange(mulu_list)

        # 问题目录标记
        verify_res = verify_mulu(mulu_list)


        all_mulu_list.append('\n'.join(mulu_list))
        all_verify_res_list.append(verify_res)


    # 打印整理结果 ------------------
    print('all_mulu_list: {}'.format(all_mulu_list))
    print('all_verify_res_list: {}'.format(all_verify_res_list))
    # -----------------------------

    # 保存整理结果 ----------------------------
    df.loc[:, '[整理]目录'] = all_mulu_list
    df.loc[:, '[整理]目录审核结果'] = all_verify_res_list
    df.to_excel(excel_path, index=0)
    # ---------------------------------------

    input("按任意键退出...")